<template>
  <el-container class="order-container">
    <!-- 搜索区域 -->
    <el-header class="search-header">
      <el-row :gutter="20" justify="space-between" align="middle">
        <el-col :span="6">
          <el-input
            v-model="searchForm.courseName"
            placeholder="课程名"
            clearable
            prefix-icon="el-icon-search"
            class="search-input"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.consultantName"
            placeholder="咨询师"
            clearable
            prefix-icon="el-icon-menu"
            class="search-input"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.userName"
            placeholder="用户名"
            clearable
            prefix-icon="el-icon-user-solid"
            class="search-input"
          />
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
            :loading="loading"
            class="search-button"
          >
            <span class="search-text">搜 索</span>
            <el-icon class="animate__animated animate__pulse search-icon"><Loading /></el-icon>
          </el-button>
        </el-col>
      </el-row>
    </el-header>

    <!-- 订单表格 -->
    <el-main class="main-content">
      <el-table
        :data="orders"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载订单数据中..."
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="courseId" label="订单编号" width="180" />
        <el-table-column prop="userName" label="用户名" width="150" />
        <el-table-column prop="image" label="课程图片" width="150">
          <template #default="scope">
            <img :src="`http://localhost:8080/img?imgUrl=${scope.row.image}`"
                 alt="Image" style="width: 100px; height: 60px; object-fit: cover;"/>
          </template>
          </el-table-column>
        <el-table-column prop="courseName" label="课程名称" width="200" />
        <el-table-column prop="consultantName" label="咨询师" width="150" />
        <el-table-column prop="actualPayment" label="订单金额" width="120"/>
        <el-table-column prop="paymentStatus" label="支付状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.orderStatus === '已完成' ? 'success' : 'warning'">
              {{ row.paymentStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseDate" label="下单时间" width="180">
          <template #default="{ row }">{{ formatDate(row.purchaseDate) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      :width="isMobile ? '95%' : '70%'"
      class="detail-dialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-skeleton :loading="detailLoading" animated>
        <template #template>
          <el-skeleton-item variant="h1" />
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" />
        </template>
        <template #default>
          <el-row :gutter="20" class="detail-row">
            <el-col :span="12">
              <el-descriptions bordered column="1">
                <el-descriptions-item label="订单编号">{{ detailData.orderId }}</el-descriptions-item>
                <el-descriptions-item label="下单时间">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="课程价格">¥{{ detailData.totalAmount }}</el-descriptions-item>
                <el-descriptions-item label="支付状态">
                  <el-tag :type="detailData.paymentStatus === '已支付' ? 'success' : 'warning'">
                    {{ detailData.paymentStatus }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions bordered column="1">
                <el-descriptions-item label="课程名称">{{ detailData.courseName }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ detailData.userName }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ detailData.remark || '无' }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
          <div class="detail-image">
            <img v-if="detailData.image" :src="`http://localhost:8080/img?imgUrl=${detailData.image}`" alt="课程图片" />
          </div>
        </template>
      </el-skeleton>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, View, Loading } from '@element-plus/icons-vue';
import orderHttp from '@/http/http.js';
import dayjs from 'dayjs';
import { ElSkeleton, ElSkeletonItem, ElDescriptions, ElTag } from 'element-plus';

// 响应式数据
const orders = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isMobile = ref(window.innerWidth < 768);
const detailLoading = ref(false);

// 分页配置
const currentPage = ref(1);
const pageSize = ref(4);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  courseName: '',
  consultantName: '',
  userName: ''
});

// 详情数据
const detailData = reactive({
  orderId: '',
  createTime: '',
  courseName: '',
  totalAmount: 0,
  paymentStatus: '',
  userName: '',
  remark: '',
  image: ''
});

// API配置
const api = {
  fetchOrders: (params) => orderHttp.get('/lzs/courseOrder', { params }),
  searchOrders: (params) => orderHttp.get('/lzs/courseOrder/searchDy', { params })
};



const fetchOrders = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    const res = await api.fetchOrders(params);
    if (res.code === 200) {
      orders.value = res.data.list.map(item => ({
        ...item,
        image: item.image ? item.image : 'default-image.jpg'
      }));
      total.value = res.data.total;
    }
  } catch (error) {
    handleError(error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  try {
    loading.value = true;
    currentPage.value = 1;
    
    const params = {
      pageNum: 1,
      pageSize: pageSize.value,
      ...searchForm
    };

    const res = await api.searchOrders(params);
    if (!res.data || res.code !== 200) throw new Error(res.message || '搜索失败');

    orders.value = res.data.list || [];
    total.value = Number(res.data.total) || 0;
  } catch (error) {
    handleError(error);
    orders.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchOrders();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrders();
};

const handleDetail = (row) => {
  Object.assign(detailData, row);
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const resetForm = () => {
  Object.keys(detailData).forEach(key => detailData[key] = '');
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const handleError = (error) => {
  console.error('API Error:', error);
  ElMessage.error(error.message || '操作失败');
};

onMounted(() => {
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth < 768;
  });
  fetchOrders();
});
</script>

<style scoped>
.order-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  min-height: 100vh;
}

.search-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
}

.main-content {
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}

/* 弹窗增强 */
.detail-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.el-descriptions {
  margin-bottom: 20px;
}

.detail-image {
  margin-top: 20px;
  text-align: center;
}

.detail-image img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

/* 动态贴纸 */
.animate__pulse {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.search-icon {
  margin-left: 8px;
  animation: bounce 2s ease-in-out infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-3px); }
}

/* 表格优化 */
.el-table th {
  background-color: #f8f9fa !important;
  color: #409eff;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-pagination {
    display: flex-wrap;
  }
  
  .el-col-6 {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>